﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using wojilu.Apps.Qycms.Domain;
using wojilu.IO;
using wojilu.Members.Interface;
using wojilu.Members.Sites.Domain;
using wojilu.Members.Sites.Service;
using wojilu.Members.Users.Domain;
using wojilu.Web.Controller.Common;
using wojilu.Web.Controller.Htmls;
using wojilu.Web.Mvc.Attr;

namespace wojilu.Web.Controller.Admin.Qycms
{
    public class ArticleController : BaseController
    {
        public virtual IAdminLogService<SiteLog> logService { get; set; }

        public ArticleController()
        {
            logService = new SiteLogService();
        }

        private void setpublic()
        {
            User user = ctx.viewer.obj as User;
            var modelPowerGroup = PowerGroup.findById(user.GroupId);
            bind("powergroup", modelPowerGroup);
        }

        [HttpGet]
        public virtual void Article_Window()
        {
            SetPublic();
            setpublic();
            set("load", to(new AdminController().Load) + "?");
            set("inputtext", ctx.Get("inputtext"));
            set("iframename", ctx.Get("iframename"));
            set("checkfrom", ctx.Get("checkfrom"));
            set("getbyid", ctx.Get("getbyid"));
            set("digheight", ctx.GetInt("digheight"));
            var lng = DefaultLng;
            set("lng", lng);
            set("max", ctx.GetInt("max"));
            var mlist = Model.find(" isclass = 1 order by id asc").list();
            bind("modelarray", mlist);

            var typelist = TypeList.find(" topid=0 and isclass = 1 and lng=:l order by pid asc,id asc").set("l", lng).list();
            var tlist = new List<TypeList>();
            foreach (var row in typelist)
            {
                tlist.Add(row);
                gettypelist(ref tlist, row.Child);
            }
            bind("typelist", tlist);

            var slist = SubjectList.find(" isclass = 1 order by pid ").list();
            bind("slist", slist);
        }

        [HttpGet]
        public virtual void SctypeList()
        {
            var mid = ctx.Get("mid");
            var optiontitle = ctx.Get("optiontitle");
            var isbase = ctx.Get("isbase");
            var islinkd = ctx.Get("islinkd");
            var lng = ctx.Get("lng");
            var builder = new MyStringBuilder();
            builder.Append("<option value=\"0\">" + optiontitle + "</option>");
            var typelist = TypeList.find(" topid=0 and isclass = 1 and mid=:m and lng=:l order by pid asc,id asc").set("m", mid).set("l", lng).list();
            var tlist = new List<TypeList>();
            foreach (var row in typelist)
            {
                tlist.Add(row);
                getmtypelist(ref tlist, row.MChild);
            }
            foreach (var row in tlist)
            {
                var level = String.Empty;
                for (var i = 0; i < row.level; i++)
                {
                    level += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                }
                level += "├─&nbsp;";
                builder.Append("<option value=\"" + row.Id + "\">" + level + row.typename + "</option>");
            }
            ctx.web.ResponseWrite(builder.ToString());
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void ScsubList()
        {
            var mid = ctx.Get("mid");
            var optiontitle = ctx.Get("optiontitle");
            var lng = ctx.Get("lng");
            var builder = new MyStringBuilder();
            builder.Append("<option value=\"0\">" + optiontitle + "</option>");
            var list = SubjectList.find(" mid=:m and lng=:l order by pid asc,id asc").set("m", mid).set("l", lng).list();
            foreach(var row in list)
            {
                builder.Append("<option value=\"" + row.Id + "\">" + row.subjectname + "</option>");
            }
            ctx.web.ResponseWrite(builder.ToString());
            ctx.web.ResponseEnd();
        }

        [HttpGet, HttpPost]
        public virtual void InfoLinked()
        {
            SetPublic();
            setpublic();
            set("load", to(new AdminController().Load) + "?");
            var lng = ctx.Get("lng");
            var mid = ctx.GetInt("mid");
            var aid = ctx.GetInt("aid");
            var tid = ctx.GetInt("tid");
            var sid = ctx.GetInt("sid");
            var isclass = ctx.GetInt("isclass");
            var isbase = ctx.GetInt("isbase");
            var islink = ctx.GetInt("islink");
            var ismess = ctx.GetInt("ismess");
            var isorder = ctx.GetInt("isorder");
            var purview = ctx.GetInt("purview");
            var eqid = ctx.GetInt("eqid");
            var ordersearch = ctx.Get("ordersearch");
            var serchekey = ctx.Get("serchekey");
            
            var condition = " lng='" + lng + "'";
            DataPage<Document> list = null;
            Int32 maxperpage = ctx.PostInt("MaxPerPage");
            Int32 page_id = ctx.PostInt("page_id") + 1;
            String limitkey = ctx.Get("limitkey");
            String limitclass = ctx.Get("limitclass");

            if (mid > 0) condition += " and mid = " + mid ;
            if (aid > 0) condition += " and aid = " + aid;
            if (tid > 0) condition += " and tid in (" + GetChildStr(tid, true) + ")";
            if (sid > 0) condition += " and sid = " + sid;
            switch(isclass)
            {
                case 1:
                    condition += " and isclass = 1";
                    break;

                case 2:
                    condition += " and isclass = 0";
                    break;
            }
            condition += " and isbase = " + isbase;
            switch (islink)
            {
                case 1:
                    condition += " and islink = 1";
                    break;

                case 2:
                    condition += " and islink = 0";
                    break;
            }
            switch (ismess)
            {
                case 1:
                    condition += " and ismess = 1";
                    break;

                case 2:
                    condition += " and ismess = 0";
                    break;
            }
            if (isorder > 0) condition += " and isorder = " + isorder;
            if (purview > 0) condition += " and purview = " + purview;
            if (!serchekey.StrIsNullOrEmpty()) condition += " and title like '%" + serchekey + "%'";

            if (strUtil.IsNullOrEmpty(limitkey)) limitkey = "id";
            if (strUtil.IsNullOrEmpty(limitclass)) limitclass = "desc";
            condition += " order by " + limitkey + " " + limitclass;
            CurrentRequest.setCurrentPage(page_id);
            list = Document.findPage(condition, maxperpage);
            if (ctx.web.postValueAll().Count == 0)
            {
                ctx.web.ResponseWrite(list.RecordCount.ToString());
                ctx.web.ResponseEnd();
            }
            bind("list", list.Results);
        }

        protected List<TypeList> gettypelist(ref List<TypeList> list, List<TypeList> clist)
        {
            foreach (var row in clist)
            {
                list.Add(row);
                gettypelist(ref list, row.Child);
            }
            return list;

        }

        protected List<TypeList> getmtypelist(ref List<TypeList> list, List<TypeList> clist)
        {
            foreach (var row in clist)
            {
                list.Add(row);
                getmtypelist(ref list, row.MChild);
            }
            return list;

        }

        protected String GetChildStr(Int64 tid, Boolean isNow)
        {
            var str = String.Empty;
            if (isNow)
            {
                str += tid + ",";
            }
            GetChildStr(tid, ref str);
            if (str.EndsWith(","))
            {
                str = str.Remove(str.Length - 1, 1);
            }
            return str;
        }

        private void GetChildStr(Int64 tid, ref String str)
        {
            var list = TypeList.find("upid = " + tid).list();
            foreach (var row in list)
            {
                str += row.Id + ",";
                GetChildStr(row.Id, ref str);
            }
        }

        [HttpGet, HttpPost]
        public virtual void ArticleList()
        {
            SetPublic();
            setpublic();
            set("load", to(new AdminController().Load) + "?");
            set("view", to(new QycmsController().Admin_Tab_List));
            DataPage<Document> list = null;
            Int32 maxperpage = ctx.PostInt("MaxPerPage");
            Int32 page_id = ctx.PostInt("page_id") + 1;
            String limitkey = ctx.Get("limitkey");
            String limitclass = ctx.Get("limitclass");
            var condition = " lng='" + DefaultLng + "'";
            var serchekey = ctx.Get("serchekey");
            if (!serchekey.StrIsNullOrEmpty())
            {
                condition += " and title like '%" + serchekey + "%'";
            }
            var dlid = ctx.GetInt("dlid");
            if (dlid > 0)
            {
                condition += " and recommend like '%" + dlid + "%'";
            }
            var mid = ctx.GetInt("mid");
            if (mid > 0)
            {
                condition += " and mid = " + mid;
            }
            var sid = ctx.GetInt("sid");
            if (sid > 0)
            {
                condition += " and sid = " + sid;
            }
            var tid = ctx.GetInt("tid");
            if (tid > 0)
            {
                condition += " and tid in(" + GetChildStr(tid, true) + ")";
            }

            var aid = ctx.GetInt("aid");
            if (aid > 0)
            {
                condition += " and aid = " + aid;
            }
            var ishtml = ctx.GetInt("ishtml");
            switch (ishtml)
            {
                case 1:
                    condition += " and ishtml = 1";
                    break;

                case 2:
                    condition += " and ishtml = 0";
                    break;
            }
            var isorder = ctx.GetInt("isorder");
            switch (isorder)
            {
                case 1:
                    condition += " and isorder = 1";
                    break;

                case 2:
                    condition += " and isorder = 0";
                    break;
            }
            var islink = ctx.GetInt("islink");
            switch (islink)
            {
                case 1:
                    condition += " and islink = 1";
                    break;

                case 2:
                    condition += " and islink = 0";
                    break;
            }
            var isclass = ctx.GetInt("isclass");
            switch (isclass)
            {
                case 1:
                    condition += " and isclass = 1";
                    break;

                case 2:
                    condition += " and isclass = 0";
                    break;
            }
            var isbase = ctx.GetInt("isbase");
            switch (isbase)
            {
                case 1:
                    condition += " and isbase = 1";
                    break;

                case 2:
                    condition += " and isbase = 0";
                    break;
            }
            var ismess = ctx.GetInt("ismess");
            switch (ismess)
            {
                case 1:
                    condition += " and ismess = 1";
                    break;

                case 2:
                    condition += " and ismess = 0";
                    break;
            }
            if (strUtil.IsNullOrEmpty(limitkey)) limitkey = "id";
            if (strUtil.IsNullOrEmpty(limitclass)) limitclass = "desc";
            condition += " order by " + limitkey + " " + limitclass;
            CurrentRequest.setCurrentPage(page_id);
            list = Document.findPage(condition, maxperpage);
            if (ctx.web.postValueAll().Count == 0)
            {
                ctx.web.ResponseWrite(list.RecordCount.ToString());
                ctx.web.ResponseEnd();
            }
            bind("list", list.Results);
        }

        [HttpGet]
        public virtual void ArticleSearch()
        {
            SetPublic();
            setpublic();
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            set("digheight", ctx.GetInt("digheight"));
            set("lng", DefaultLng);
            var modelarray = Model.find(" isbase=:i order by id asc").set("i", 0).list();
            bind("modelarray", modelarray);
            var mid = ctx.GetInt("mid");
            set("mid", mid);
            var tid = ctx.GetInt("tid");
            set("tid", tid);
            var subjectlist = new List<SubjectList>();
            if (mid > 0)
            {
                subjectlist = SubjectList.find(" mid=:m and lng=:l").set("m", mid).set("l", DefaultLng).list();
            }
            else
            {
                subjectlist = SubjectList.find(" lng=:l").set("l", DefaultLng).list();
            }
            bind("subjectlist", subjectlist);
            var list = TypeList.find(" topid=0 and isclass = 1 and lng=:l order by pid asc,id asc").set("l", DefaultLng).list();
            var list1 = new List<TypeList>();
            foreach (var row in list)
            {
                list1.Add(row);
                getmtypelist(ref list1, row.MChild);
            }
            bind("list", list1);
            var doclabel = new List<Document_Label>();
            if (mid > 0)
            {
                doclabel = Document_Label.find(" mid=:m and lng=:l").set("m", mid).set("l", DefaultLng).list();
            }
            else
            {
                doclabel = Document_Label.find(" lng=:l").set("l", DefaultLng).list();
            }
            bind("doclabel", doclabel);
        }

        [NonVisit]
        public void type_list(ref List<TypeList> list, TypeList row)
        {
            var condition = " lng='" + DefaultLng + "' and upid = " + row.Id;
            DataPage<TypeList> list1 = null;
            Int32 maxperpage = ctx.PostInt("MaxPerPage");
            Int32 page_id = ctx.PostInt("page_id") + 1;
            String limitkey = ctx.Get("limitkey");
            String limitclass = ctx.Get("limitclass");
            var mid = ctx.GetInt("mid");
            if (mid > 0)
            {
                condition += " and mid = " + mid;
            }
            if (strUtil.IsNullOrEmpty(limitkey)) limitkey = "pid";
            if (strUtil.IsNullOrEmpty(limitclass)) limitclass = "asc";
            condition += " order by " + limitkey + " " + limitclass + ",id asc";
            list1 = wojilu.Apps.Qycms.Domain.TypeList.findPage(condition, maxperpage);
            foreach (var row1 in list1.Results)
            {
                list.Add(row1);
                type_list(ref list, row1);
            }
        }

        [HttpGet]
        public virtual void ArticleAdd()
        {
            SetPublic();
            setpublic();
            target(ArticleAddDo);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            set("refalse", "1");
            set("tab", "true");
            set("lng", DefaultLng);
            var mid = ctx.GetInt("mid");
            set("mid", mid);
            var m = Model.findById(mid);
            bind("modelview", m);
            var tid = ctx.GetInt("tid");
            set("tid", tid);
            var tsnstyle = m.tsnstyle;
            set("tsn", tsnstyle.GetReplace("{datetime}", DateTime.Now.ToString("yyyyMMddHHmmss")).GetReplace("{s}", Rand.MakeRandomString("0123456789", 3)));
            set("adminurl", configsService.GetValue("domain"));
            var modelatt = new List<Model_Att>();
            if (mid > 1)
            {
                modelatt = Model_Att.find(" mid =:m and isclass = 1 order by pid asc,id asc").set("m", mid).list();
            }
            else
            {
                modelatt = Model_Att.find(" (mid =:m or (mid = 0 and Id <=8)) and isclass = 1 order by pid asc,id asc").set("m", mid).list();
            }
            bind("modelatt", modelatt);
            set("input_click", configsService.GetValue("input_click").ToInt());
            var memberpuvlist = Member_Class.findAll();
            bind("memberpuvlist", memberpuvlist);
            var formarray = Form_Group.findAll();
            bind("formarray", formarray);
            var subjectlistarray = SubjectList.find(" mid=:m order by pid asc,id asc").set("m", mid).list();
            bind("subjectlistarray", subjectlistarray);
            var condition = " lng='" + DefaultLng + "' and upid = 0 and mid =" + mid;
            condition += " order by pid asc,id asc";
            var list = wojilu.Apps.Qycms.Domain.TypeList.find(condition).list();
            var list1 = new List<TypeList>();
            foreach (var row in list)
            {
                list1.Add(row);
                type_list(ref list1, row);
            }
            condition = " lng='" + DefaultLng + "' and upid >0 and mid =" + mid;
            condition += " order by pid asc,id asc";
            list = wojilu.Apps.Qycms.Domain.TypeList.find(condition).list();
            foreach (var row in list)
            {
                var bol = true;
                foreach (var row1 in list1)
                {
                    if (row.Id == row1.Id)
                    {
                        bol = false;
                        break;
                    }
                }
                if (bol)
                {
                    list1.Add(row);
                    type_list(ref list1, row);
                }
            }
            bind("typelist", list1);
            var doclabel = new List<Document_Label>();
            if (mid > 0)
            {
                doclabel = Document_Label.find("lng=:l and mid=:m order by id desc").set("l", DefaultLng).set("m", mid).list();
            }
            else
            {
                doclabel = Document_Label.find("lng=:l order by id desc").set("l", DefaultLng).list();
            }
            bind("labellist", doclabel);
            set("input_isdellink", configsService.GetValue("input_isdellink").ToInt());
            set("input_color", configsService.GetValue("input_color"));
        }

        [HttpPost]
        public virtual void ArticleAddDo()
        {
            var mid = ctx.PostInt("mid");
            var m = Model.findById(mid);
            var d = new Document();
            d.mid = mid;
            d.lng = ctx.Post("lng");
            d.aid = 1;
            var tid = ctx.PostInt("tid");
            d.tid = tid;
            d.pid = 50;
            d.extid = ctx.Post("extid[]").StrIsNullOrEmpty() ? "0" : ctx.Post("extid[]");
            var recommend = ctx.Post("recommend[]");
            if (!recommend.StrIsNullOrEmpty())
            {
                recommend = "," + recommend + ",";
            }
            d.recommend = recommend;
            d.fgid = ctx.PostInt("fgid");
            d.purview = ctx.PostInt("purview");
            d.uptime = DateTime.Now;
            d.addtime = ctx.Post("addtim").ToDateTime();
            d.click = ctx.PostInt("click");
            d.islink = ctx.PostInt("islink");
            d.link = ctx.Post("link");
            d.headtitle = ctx.Post("headtitle");
            var tags = ctx.Post("tags");
            if (!tags.StrIsNullOrEmpty())
            {
                tags = "," + tags + ",";
            }
            d.tags = tags;
            d.keywords = ctx.Post("keywords");
            d.ishtml = ctx.PostInt("ishtml");
            d.istemplates = ctx.PostInt("istemplates");
            var template = ctx.Post("templte");
            if (!template.StrIsNullOrEmpty())
            {
                d.template = template;
            }
            else
            {
                d.template = "article_read";
            }
            d.sid = ctx.PostInt("sid");
            var t = TypeList.findById(tid);
            if (t != null)
            {
                if (t.topid == 0)
                {
                    d.filepath = t.dirname;
                }
                else
                {
                    d.filepath = t.dirpath;
                }
            }
            d.filepage = ctx.PostInt("filepage") == 0 ? 1 : ctx.PostInt("filepage");
            d.ismess = ctx.PostInt("ismessage");
            var linkdid = ctx.Post("linkdid");
            if (!linkdid.StrIsNullOrEmpty())
            {
                d.linkdid = linkdid.TrimEnd(',');
            }
            if (((User)ctx.viewer.obj).inputclassid == 1)
            {
                d.isclass = 1;
            }
            else
            {
                d.isclass = 0;
            }
            d.isorder = ctx.PostInt("isorder");
            d.ktid = ctx.PostInt("ktid");
            d.isbase = ctx.PostInt("isbase");
            var tsn = ctx.Post("tsn");
            if (tsn.StrIsNullOrEmpty())
            {
                d.tsn = m.tsnstyle.GetReplace("{datetime}", DateTime.Now.ToString("yyyyMMddHHmmss")).GetReplace("{s}", Rand.MakeRandomString("0123456789", 3));
            }
            else
            {
                d.tsn = tsn;
            }
            d.color = ctx.Post("color");
            Result result = d.insert();
            var filename = ctx.Post("filename");
            if (filename.StrIsNullOrEmpty())
            {
                filename = d.Id.ToString();
            }
            d.filename = filename;
            d.update();
            var ma = new List<Model_Att>();
            if (mid > 1)
            {
                ma = Model_Att.find(" mid =:m and isclass = 1 order by pid asc,id asc").set("m", mid).list();
            }
            else
            {
                ma = Model_Att.find(" (mid =:m or (mid = 0 and Id <=8)) and isclass = 1 order by pid asc,id asc").set("m", mid).list();
            }
            var dsql = String.Empty;
            var dasql1 = String.Empty;
            var dasql2 = String.Empty;
            foreach(var row in ma)
            {
                var attrname = ctx.Post(row.attrname);
                switch (row.attrname)
                {
                    case "content":
                        #region content
                        attrname = ctx.PostHtmlAll(row.attrname);
                        if (row.inputtype == "editor")
                        {
                            //清除非本站的链接。
                            if (ctx.PostInt("input_isdellink") == 1)
                            {
                                var siteurl = SiteUrl();
                                var regex = new Regex(@"(?is)<a[^>]*?href=(['""\s])(?:(?!" + siteurl + @")[^'""\s])*\1[^>]*?>(.*?)</a>");
                                attrname = regex.Replace(attrname, "$2");
                            }
                            if (ctx.PostInt("donwloadpic") == 1)
                            {
                                var pattern = string.Empty;
                                pattern = "<img.*? src=(?:\"|')?(.*?)(?:\"|')? .*?>";
                                MatchCollection matchs = Regex.Matches(attrname, pattern, RegexOptions.IgnoreCase);
                                foreach (Match match in matchs)
                                {
                                    if (match.Groups.Count > 1)
                                    {
                                        string str2 = match.Groups[1].Value;
                                        string replacement = string.Empty;
                                        if (!this.a(str2))
                                        {
                                            replacement = this.SaveLocalImage(str2);
                                            if (replacement != string.Empty)
                                            {
                                                attrname = Regex.Replace(attrname, str2, replacement, RegexOptions.IgnoreCase);
                                            }
                                        }
                                    }
                                }
                                pattern = "<embed.*? src=(?:\"|')?(.+\\.(swf|))(?:\"|')?.*?>";
                                matchs = Regex.Matches(attrname, pattern, RegexOptions.IgnoreCase);
                                foreach (Match match in matchs)
                                {
                                    if (match.Groups.Count > 1)
                                    {
                                        string str2 = match.Groups[1].Value;
                                        string replacement = string.Empty;
                                        if (!this.a(str2))
                                        {
                                            replacement = this.SaveLocalImage(str2);
                                            if (replacement != string.Empty)
                                            {
                                                attrname = Regex.Replace(attrname, str2, replacement, RegexOptions.IgnoreCase);
                                            }
                                        }
                                    }
                                }
                            }
                            if (configsService.GetValue("is_keylink") == "1")
                            {
                                var tags1 = ctx.Post("tags");
                                var keylinklist = KeyLink.findAll();
                                //var tids = StringHelper.SplitInt(new YBBTypeList().GetChildStr(tid, true), ",");
                                //var queryResult = from p in keylinklist where (tids.Contains((int)p.tid)) select p;
                                //keylinklist = new SourceList<keylink>(queryResult.ToList());
                                var strArray2 = tags1.SplitString();
                                for (int i = 0; i < strArray2.Length; i++)
                                {
                                    var linkurl = string.Empty;
                                    var bol = false;
                                    foreach (var rowkey in keylinklist)
                                    {
                                        if (rowkey.keywordname == strArray2[i])
                                        {
                                            if (rowkey.islink == 1)
                                            {
                                                linkurl = "<a class=\"taglink\" title=\"" + rowkey.keywordname + "\" href=\"" + rowkey.linkurl + "\" target=\"_blank\">" + rowkey.keywordname + "</a>";
                                            }
                                            else
                                            {
                                                linkurl = "<a class=\"taglink\" title=\"" + rowkey.keywordname + "\" href=\"" + sys.Path.Root + "Search/TagList.aspx?at=taglist&tagkey=" + DataSecurity.UrlEncodes(rowkey.keywordname) + "\" target=\"_blank\">" + rowkey.keywordname + "</a>";
                                            }
                                            bol = true;
                                            break;
                                        }
                                    }
                                    if (!bol)
                                    {
                                        linkurl = "<a class=\"taglink\" title=\"" + strArray2[i] + "\" href=\"" + sys.Path.Root + "Search/TagList.aspx?at=taglist&tagkey=" + DataSecurity.UrlEncodes(strArray2[i]) + "\" target=\"_blank\">" + strArray2[i] + "</a>";
                                    }
                                    attrname = Regex.Replace(attrname, strArray2[i], linkurl);
                                }
                            }
                            var description = ctx.Post("description");
                            if (description.StrIsNullOrEmpty())
                            {
                                if (configsService.GetValue("input_isdes") == "1")
                                {
                                    var jj = attrname.NoHTML();
                                    jj = StringHelper.CutStrings(jj, TypeCon.StrToInt(configsService.GetValue("input_isdescription")));
                                    if (!description.StrIsNullOrEmpty())
                                    {
                                        d.description = description;
                                    }
                                    else
                                    {
                                        d.description = jj;
                                    }
                                }
                                else
                                {
                                    d.description = description;
                                }
                            }
                            d.update();
                        }
                        var dc = Document_Content.find(" did =" + d.Id).first();
                        if (dc != null)
                        {
                            dc.content = attrname;
                            dc.update();
                        }
                        else
                        {
                            dc = new Document_Content();
                            dc.did = d.Id;
                            dc.content = attrname;
                            dc.insert();
                        }
                        #endregion
                        break;

                    case "wapcontent":
                        #region content
                        attrname = ctx.PostHtmlAll(row.attrname);
                        if (row.inputtype == "editor")
                        {
                            //清除非本站的链接。
                            if (ctx.PostInt("input_isdellink") == 1)
                            {
                                var siteurl = SiteUrl();
                                var regex = new Regex(@"(?is)<a[^>]*?href=(['""\s])(?:(?!" + siteurl + @")[^'""\s])*\1[^>]*?>(.*?)</a>");
                                attrname = regex.Replace(attrname, "$2");
                            }
                            if (ctx.PostInt("donwloadpic") == 1)
                            {
                                var pattern = string.Empty;
                                pattern = "<img.*? src=(?:\"|')?(.*?)(?:\"|')? .*?>";
                                MatchCollection matchs = Regex.Matches(attrname, pattern, RegexOptions.IgnoreCase);
                                foreach (Match match in matchs)
                                {
                                    if (match.Groups.Count > 1)
                                    {
                                        string str2 = match.Groups[1].Value;
                                        string replacement = string.Empty;
                                        if (!this.a(str2))
                                        {
                                            replacement = this.SaveLocalImage(str2);
                                            if (replacement != string.Empty)
                                            {
                                                attrname = Regex.Replace(attrname, str2, replacement, RegexOptions.IgnoreCase);
                                            }
                                        }
                                    }
                                }
                                pattern = "<embed.*? src=(?:\"|')?(.+\\.(swf|))(?:\"|')?.*?>";
                                matchs = Regex.Matches(attrname, pattern, RegexOptions.IgnoreCase);
                                foreach (Match match in matchs)
                                {
                                    if (match.Groups.Count > 1)
                                    {
                                        string str2 = match.Groups[1].Value;
                                        string replacement = string.Empty;
                                        if (!this.a(str2))
                                        {
                                            replacement = this.SaveLocalImage(str2);
                                            if (replacement != string.Empty)
                                            {
                                                attrname = Regex.Replace(attrname, str2, replacement, RegexOptions.IgnoreCase);
                                            }
                                        }
                                    }
                                }
                            }
                            if (configsService.GetValue("is_keylink") == "1")
                            {
                                var tags1 = ctx.Post("tags");
                                var keylinklist = KeyLink.findAll();
                                //var tids = StringHelper.SplitInt(new YBBTypeList().GetChildStr(tid, true), ",");
                                //var queryResult = from p in keylinklist where (tids.Contains((int)p.tid)) select p;
                                //keylinklist = new SourceList<keylink>(queryResult.ToList());
                                var strArray2 = tags1.SplitString();
                                for (int i = 0; i < strArray2.Length; i++)
                                {
                                    var linkurl = string.Empty;
                                    var bol = false;
                                    foreach (var rowkey in keylinklist)
                                    {
                                        if (rowkey.keywordname == strArray2[i])
                                        {
                                            if (rowkey.islink == 1)
                                            {
                                                linkurl = "<a class=\"taglink\" title=\"" + rowkey.keywordname + "\" href=\"" + rowkey.linkurl + "\" target=\"_blank\">" + rowkey.keywordname + "</a>";
                                            }
                                            else
                                            {
                                                linkurl = "<a class=\"taglink\" title=\"" + rowkey.keywordname + "\" href=\"" + sys.Path.Root + "Search/TagList.aspx?at=taglist&tagkey=" + DataSecurity.UrlEncodes(rowkey.keywordname) + "\" target=\"_blank\">" + rowkey.keywordname + "</a>";
                                            }
                                            bol = true;
                                            break;
                                        }
                                    }
                                    if (!bol)
                                    {
                                        linkurl = "<a class=\"taglink\" title=\"" + strArray2[i] + "\" href=\"" + sys.Path.Root + "Search/TagList.aspx?at=taglist&tagkey=" + DataSecurity.UrlEncodes(strArray2[i]) + "\" target=\"_blank\">" + strArray2[i] + "</a>";
                                    }
                                    attrname = Regex.Replace(attrname, strArray2[i], linkurl);
                                }
                            }
                            var description = ctx.Post("description");
                            if (description.StrIsNullOrEmpty())
                            {
                                if (configsService.GetValue("input_isdes") == "1")
                                {
                                    var jj = attrname.NoHTML();
                                    jj = StringHelper.CutStrings(jj, TypeCon.StrToInt(configsService.GetValue("input_isdescription")));
                                    if (!description.StrIsNullOrEmpty())
                                    {
                                        d.description = description;
                                    }
                                    else
                                    {
                                        d.description = jj;
                                    }
                                }
                                else
                                {
                                    d.description = description;
                                }
                            }
                            d.update();
                        }
                        dc = Document_Content.find(" did =" + d.Id).first();
                        if (dc != null)
                        {
                            dc.wapcontent = attrname;
                            dc.update();
                        }
                        else
                        {
                            dc = new Document_Content();
                            dc.did = d.Id;
                            dc.wapcontent = attrname;
                            dc.insert();
                        }
                        #endregion
                        break;

                    default:
                        switch (row.inputtype)
                        {
                            case "htmltext":
                                attrname = StringHelper.TextToHTML(attrname);
                                break;

                            case "img":
                                if (attrname.StartsWith("../"))
                                {
                                    attrname = Right(attrname, attrname.Length - 3);
                                }
                                break;

                            case "editor":
                                attrname = ctx.PostHtmlAll(row.attrname);
                                break;
                        }
                        var ism = Model_Att.find(" mid = 0 and  issys = 0 and attrname=:a").set("a", row.attrname).first();
                        if (ism != null)
                        {
                            dsql += "update ybb_document set " + row.attrname + " = '" + attrname + "' where Id =" + d.Id + ";";
                        }
                        else
                        {
                            dasql1 += row.attrname + ",";
                            dasql2 += "'" + attrname + "',";
                        }
                        break;
                }
            }
            if (!dsql.StrIsNullOrEmpty())
            {
                db.RunSql<Document>(dsql);
            }
            if (!dasql1.StrIsNullOrEmpty())
            {
                dsql = "insert into ybb_document_attr (did ," + dasql1.TrimEnd(',') + ") values (" + d.Id + ",'" + dasql2.TrimEnd(',') + "');";
                db.RunSql<Document_Attr>(dsql);
            }
            var albumlist = ctx.Post("albumlist");
            var albumliststr = albumlist.SplitString("|");
            var picname = ctx.Post("picname[]");
            var picnamestr = picname.SplitString();
            var filedes = ctx.Post("filedes[]");
            var filedesstr = filedes.SplitString();
            if (albumliststr.Length > 0)
            {
                for (var i = 0; i < albumliststr.Length - 1; i++)
                {
                    var documentalbum = new Document_Album();
                    documentalbum.did = d.Id;
                    if (picnamestr.Length == 0)
                    {
                        documentalbum.picname = string.Empty;
                    }
                    else
                    {
                        documentalbum.picname = picnamestr[i];
                    }
                    if (filedesstr.Length == 0)
                    {
                        documentalbum.filedes = string.Empty;
                    }
                    else
                    {
                        documentalbum.filedes = filedesstr[i];
                    }
                    documentalbum.picfile = albumliststr[i];
                    documentalbum.addtime = DateTime.Now;
                    documentalbum.insert();
                }
            }
            if (ctx.HasErrors)
            {
                ctx.web.ResponseWrite(ctx.errors.ErrorsText);
            }
            else
            {
                ctx.web.ResponseWrite("true");
            }
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void ArticleEdit(Int64 Id)
        {
            SetPublic();
            setpublic();
            target(ArticleEditDo, Id);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            set("refalse", "1");
            set("tab", "true");
            set("type", ctx.Get("type"));
            var d = Document.findById(Id);
            bind("readview", d);
            var read = db.RunTable("select ybb_document.*,ybb_document_content.*,ybb_document_attr.* from ybb_document left join ybb_document_content on ybb_document.id=ybb_document_content.did left join ybb_document_attr on ybb_document.id=ybb_document_attr.did where ybb_document.id=" + Id);
            bind("read", read.Rows[0]);
            var dc = Document_Content.find(" did=:d").set("d", Id).first();
            if (dc != null)
            {
                set("dcid", dc.Id);
            }
            else
            {
                set("dcid", 0);
            }
            var da = Document_Attr.find(" did=:d").set("d", Id).first();
            if (da != null)
            {
                set("datid", da.Id);
            }
            else
            {
                set("datid", 0);
            }
            set("lng", d.lng);
            var mid = d.mid;
            set("mid", mid);
            var m = Model.findById(mid);
            bind("modelview", m);
            var tid = d.tid;
            set("tid", tid);
            var t = TypeList.findById(tid);
            bind("typeread", t);
            var tsnstyle = m.tsnstyle;
            set("tsn", tsnstyle.GetReplace("{datetime}", DateTime.Now.ToString("yyyyMMddHHmmss")).GetReplace("{s}", Rand.MakeRandomString("0123456789", 3)));
            set("adminurl", configsService.GetValue("domain").Trim('/'));
            var modelatt = new List<Model_Att>();
            if (mid > 1)
            {
                modelatt = Model_Att.find(" mid =:m and isclass = 1 order by pid asc,id asc").set("m", mid).list();
            }
            else
            {
                modelatt = Model_Att.find(" (mid =:m or (mid = 0 and Id <=8)) and isclass = 1 order by pid asc,id asc").set("m", mid).list();
            }
            bind("modelatt", modelatt);
            var memberpuvlist = Member_Class.findAll();
            bind("memberpuvlist", memberpuvlist);
            var formarray = Form_Group.findAll();
            bind("formarray", formarray);
            var doclabel = new List<Document_Label>();
            if (mid > 0)
            {
                doclabel = Document_Label.find("lng=:l and mid=:m order by id desc").set("l", DefaultLng).set("m", mid).list();
            }
            else
            {
                doclabel = Document_Label.find("lng=:l order by id desc").set("l", DefaultLng).list();
            }
            bind("labellist", doclabel);
            var subjectlistarray = SubjectList.find(" mid=:m order by pid asc,id asc").set("m", mid).list();
            bind("subjectlistarray", subjectlistarray);
            var condition = " lng='" + DefaultLng + "' and upid = 0 and mid =" + mid;
            condition += " order by pid asc,id asc";
            var list = wojilu.Apps.Qycms.Domain.TypeList.find(condition).list();
            var list1 = new List<TypeList>();
            foreach (var row in list)
            {
                list1.Add(row);
                type_list(ref list1, row);
            }
            condition = " lng='" + DefaultLng + "' and upid >0 and mid =" + mid;
            condition += " order by pid asc,id asc";
            list = wojilu.Apps.Qycms.Domain.TypeList.find(condition).list();
            foreach (var row in list)
            {
                var bol = true;
                foreach (var row1 in list1)
                {
                    if (row.Id == row1.Id)
                    {
                        bol = false;
                        break;
                    }
                }
                if (bol)
                {
                    list1.Add(row);
                    type_list(ref list1, row);
                }
            }
            bind("typelist", list1);
            set("input_isdellink", configsService.GetValue("input_isdellink").ToInt());
        }

        [HttpPost]
        public virtual void ArticleEditDo(Int64 Id)
        {
            var d = Document.findById(Id);
            var mid = ctx.PostInt("mid");
            var m = Model.findById(mid);
            var ma = new List<Model_Att>();
            if (mid > 1)
            {
                ma = Model_Att.find(" mid =:m and isclass = 1 order by pid asc,id asc").set("m", mid).list();
            }
            else
            {
                ma = Model_Att.find(" (mid =:m or (mid = 0 and Id <=8)) and isclass = 1 order by pid asc,id asc").set("m", mid).list();
            }
            var type = ctx.Post("inputclass");
            var tags = ctx.Post("tags");
            if (!tags.StrIsNullOrEmpty())
            {
                tags = "," + tags + ",";
            }
            d.tags = tags;
            d.keywords = ctx.Post("keywords");
            d.ishtml = ctx.PostInt("ishtml");
            d.istemplates = ctx.PostInt("istemplates");
            var template = ctx.Post("templte");
            d.template = template;
            d.sid = ctx.PostInt("sid");
            var tid = ctx.PostInt("tid");
            d.tid = tid;
            d.addtime = ctx.Post("addtime").ToDateTime();
            d.extid = ctx.Post("extid[]");
            var recommend = ctx.Post("recommend[]");
            if (!recommend.StrIsNullOrEmpty())
            {
                recommend = "," + recommend + ",";
            }
            d.recommend = recommend;
            d.fgid = ctx.PostInt("fgid");
            d.purview = ctx.PostInt("purview");
            d.uptime = DateTime.Now;
            d.click = ctx.PostInt("click");
            d.islink = ctx.PostInt("islink");
            d.link = ctx.Post("link");
            d.ismess = ctx.PostInt("ismessage");
            d.linkdid = ctx.Post("linkdid");
            d.isorder = ctx.PostInt("isorder");
            var filename = ctx.Post("filename");
            if (filename.StrIsNullOrEmpty())
            {
                filename = Id.ToString();
            }
            d.filename = filename;
            var t = TypeList.findById(tid);
            if (t != null)
            {
                if (t.topid == 0)
                {
                    d.filepath = t.dirname;
                }
                else
                {
                    d.filepath = t.dirpath;
                }
            }
            d.filepage = 1;
            var tsn = ctx.Post("tsn");
            if (tsn.StrIsNullOrEmpty())
            {
                d.tsn = m.tsnstyle.GetReplace("{datetime}", DateTime.Now.ToString("yyyyMMddHHmmss")).GetReplace("{s}", Rand.MakeRandomString("0123456789", 3));
            }
            else
            {
                d.tsn = tsn;
            }
            d.color = ctx.Post("color");
            d.headtitle = ctx.Post("headtitle");
            if (type == "add")
            {
                d.tsn = m.tsnstyle.GetReplace("{datetime}", DateTime.Now.ToString("yyyyMMddHHmmss")).GetReplace("{s}", Rand.MakeRandomString("0123456789", 3));
                d.insert();
            }
            else
            {
                d.update();
            }
            var dsql = String.Empty;
            var dasql = String.Empty;
            var dasql1 = String.Empty;
            var dasql2 = String.Empty;
            foreach (var row in ma)
            {
                var attrname = ctx.Post(row.attrname);
                switch (row.attrname)
                {
                    case "content":
                        #region content
                        attrname = ctx.PostHtmlAll(row.attrname);
                        if (row.inputtype == "editor")
                        {
                            //清除非本站的链接。
                            if (ctx.PostInt("input_isdellink") == 1)
                            {
                                var siteurl = SiteUrl();
                                var regex = new Regex(@"(?is)<a[^>]*?href=(['""\s])(?:(?!" + siteurl + @")[^'""\s])*\1[^>]*?>(.*?)</a>");
                                attrname = regex.Replace(attrname, "$2");
                            }
                            if (ctx.PostInt("donwloadpic") == 1)
                            {
                                var pattern = string.Empty;
                                pattern = "<img.*? src=(?:\"|')?(.*?)(?:\"|')? .*?>";
                                MatchCollection matchs = Regex.Matches(attrname, pattern, RegexOptions.IgnoreCase);
                                foreach (Match match in matchs)
                                {
                                    if (match.Groups.Count > 1)
                                    {
                                        string str2 = match.Groups[1].Value;
                                        string replacement = string.Empty;
                                        if (!this.a(str2))
                                        {
                                            replacement = this.SaveLocalImage(str2);
                                            if (replacement != string.Empty)
                                            {
                                                attrname = Regex.Replace(attrname, str2, replacement, RegexOptions.IgnoreCase);
                                            }
                                        }
                                    }
                                }
                                pattern = "<embed.*? src=(?:\"|')?(.+\\.(swf|))(?:\"|')?.*?>";
                                matchs = Regex.Matches(attrname, pattern, RegexOptions.IgnoreCase);
                                foreach (Match match in matchs)
                                {
                                    if (match.Groups.Count > 1)
                                    {
                                        string str2 = match.Groups[1].Value;
                                        string replacement = string.Empty;
                                        if (!this.a(str2))
                                        {
                                            replacement = this.SaveLocalImage(str2);
                                            if (replacement != string.Empty)
                                            {
                                                attrname = Regex.Replace(attrname, str2, replacement, RegexOptions.IgnoreCase);
                                            }
                                        }
                                    }
                                }
                            }
                            if (configsService.GetValue("is_keylink") == "1")
                            {
                                Regex regex = new Regex("(?is)<a[\\s]*class=\"taglink\"[\\s]*title=\"[^\"]*\"[^>]*?href=(['\"\\s])(?:(?<url>)[^'\"\\s])*\\1[^>]*?>(.*?)</a>");
                                attrname = regex.Replace(attrname, "$2");
                                var tags1 = ctx.Post("tags");
                                var keylinklist = KeyLink.findAll();
                                //var tids = StringHelper.SplitInt(new YBBTypeList().GetChildStr(tid, true), ",");
                                //var queryResult = from p in keylinklist where (tids.Contains((int)p.tid)) select p;
                                //keylinklist = new SourceList<keylink>(queryResult.ToList());
                                var strArray2 = tags1.SplitString();
                                for (int i = 0; i < strArray2.Length; i++)
                                {
                                    var linkurl = string.Empty;
                                    var bol = false;
                                    foreach (var rowkey in keylinklist)
                                    {
                                        if (rowkey.keywordname == strArray2[i])
                                        {
                                            if (rowkey.islink == 1)
                                            {
                                                linkurl = "<a class=\"taglink\" title=\"" + rowkey.keywordname + "\" href=\"" + rowkey.linkurl + "\" target=\"_blank\">" + rowkey.keywordname + "</a>";
                                            }
                                            else
                                            {
                                                linkurl = "<a class=\"taglink\" title=\"" + rowkey.keywordname + "\" href=\"" + sys.Path.Root + "Search/TagList.aspx?at=taglist&tagkey=" + DataSecurity.UrlEncodes(rowkey.keywordname) + "\" target=\"_blank\">" + rowkey.keywordname + "</a>";
                                            }
                                            bol = true;
                                            break;
                                        }
                                    }
                                    if (!bol)
                                    {
                                        linkurl = "<a class=\"taglink\" title=\"" + strArray2[i] + "\" href=\"" + sys.Path.Root + "Search/TagList.aspx?at=taglist&tagkey=" + DataSecurity.UrlEncodes(strArray2[i]) + "\" target=\"_blank\">" + strArray2[i] + "</a>";
                                    }
                                    attrname = Regex.Replace(attrname, strArray2[i], linkurl);
                                }
                            }
                            var description = ctx.Post("description");
                            if (description.StrIsNullOrEmpty())
                            {
                                if (configsService.GetValue("input_isdes") == "1")
                                {
                                    var jj = attrname.NoHTML();
                                    jj = StringHelper.CutStrings(jj, TypeCon.StrToInt(configsService.GetValue("input_isdescription")));
                                    if (!description.StrIsNullOrEmpty())
                                    {
                                        d.description = description;
                                    }
                                    else
                                    {
                                        d.description = jj;
                                    }
                                }
                                else
                                {
                                    d.description = description;
                                }
                            }
                            d.update();
                        }
                        var dc = Document_Content.find(" did =" + d.Id).first();
                        if (dc != null)
                        {
                            dc.content = attrname;
                            dc.update();
                        }
                        else
                        {
                            dc = new Document_Content();
                            dc.did = d.Id;
                            dc.content = attrname;
                            dc.insert();
                        }
                        #endregion
                        break;

                    case "wapcontent":
                        #region wapcontent
                        attrname = ctx.PostHtmlAll(row.attrname);
                        if (row.inputtype == "editor")
                        {
                            //清除非本站的链接。
                            if (ctx.PostInt("input_isdellink") == 1)
                            {
                                var siteurl = SiteUrl();
                                var regex = new Regex(@"(?is)<a[^>]*?href=(['""\s])(?:(?!" + siteurl + @")[^'""\s])*\1[^>]*?>(.*?)</a>");
                                attrname = regex.Replace(attrname, "$2");
                            }
                            if (ctx.PostInt("donwloadpic") == 1)
                            {
                                var pattern = string.Empty;
                                pattern = "<img.*? src=(?:\"|')?(.*?)(?:\"|')? .*?>";
                                MatchCollection matchs = Regex.Matches(attrname, pattern, RegexOptions.IgnoreCase);
                                foreach (Match match in matchs)
                                {
                                    if (match.Groups.Count > 1)
                                    {
                                        string str2 = match.Groups[1].Value;
                                        string replacement = string.Empty;
                                        if (!this.a(str2))
                                        {
                                            replacement = this.SaveLocalImage(str2);
                                            if (replacement != string.Empty)
                                            {
                                                attrname = Regex.Replace(attrname, str2, replacement, RegexOptions.IgnoreCase);
                                            }
                                        }
                                    }
                                }
                                pattern = "<embed.*? src=(?:\"|')?(.+\\.(swf|))(?:\"|')?.*?>";
                                matchs = Regex.Matches(attrname, pattern, RegexOptions.IgnoreCase);
                                foreach (Match match in matchs)
                                {
                                    if (match.Groups.Count > 1)
                                    {
                                        string str2 = match.Groups[1].Value;
                                        string replacement = string.Empty;
                                        if (!this.a(str2))
                                        {
                                            replacement = this.SaveLocalImage(str2);
                                            if (replacement != string.Empty)
                                            {
                                                attrname = Regex.Replace(attrname, str2, replacement, RegexOptions.IgnoreCase);
                                            }
                                        }
                                    }
                                }
                            }
                            if (configsService.GetValue("is_keylink") == "1")
                            {
                                Regex regex = new Regex("(?is)<a[\\s]*class=\"taglink\"[\\s]*title=\"[^\"]*\"[^>]*?href=(['\"\\s])(?:(?<url>)[^'\"\\s])*\\1[^>]*?>(.*?)</a>");
                                attrname = regex.Replace(attrname, "$2");
                                var tags1 = ctx.Post("tags");
                                var keylinklist = KeyLink.findAll();
                                //var tids = StringHelper.SplitInt(new YBBTypeList().GetChildStr(tid, true), ",");
                                //var queryResult = from p in keylinklist where (tids.Contains((int)p.tid)) select p;
                                //keylinklist = new SourceList<keylink>(queryResult.ToList());
                                var strArray2 = tags1.SplitString();
                                for (int i = 0; i < strArray2.Length; i++)
                                {
                                    var linkurl = string.Empty;
                                    var bol = false;
                                    foreach (var rowkey in keylinklist)
                                    {
                                        if (rowkey.keywordname == strArray2[i])
                                        {
                                            if (rowkey.islink == 1)
                                            {
                                                linkurl = "<a class=\"taglink\" title=\"" + rowkey.keywordname + "\" href=\"" + rowkey.linkurl + "\" target=\"_blank\">" + rowkey.keywordname + "</a>";
                                            }
                                            else
                                            {
                                                linkurl = "<a class=\"taglink\" title=\"" + rowkey.keywordname + "\" href=\"" + sys.Path.Root + "Search/TagList.aspx?at=taglist&tagkey=" + DataSecurity.UrlEncodes(rowkey.keywordname) + "\" target=\"_blank\">" + rowkey.keywordname + "</a>";
                                            }
                                            bol = true;
                                            break;
                                        }
                                    }
                                    if (!bol)
                                    {
                                        linkurl = "<a class=\"taglink\" title=\"" + strArray2[i] + "\" href=\"" + sys.Path.Root + "Search/TagList.aspx?at=taglist&tagkey=" + DataSecurity.UrlEncodes(strArray2[i]) + "\" target=\"_blank\">" + strArray2[i] + "</a>";
                                    }
                                    attrname = Regex.Replace(attrname, strArray2[i], linkurl);
                                }
                            }
                            var description = ctx.Post("description");
                            if (description.StrIsNullOrEmpty())
                            {
                                if (configsService.GetValue("input_isdes") == "1")
                                {
                                    var jj = attrname.NoHTML();
                                    jj = StringHelper.CutStrings(jj, TypeCon.StrToInt(configsService.GetValue("input_isdescription")));
                                    if (!description.StrIsNullOrEmpty())
                                    {
                                        d.description = description;
                                    }
                                    else
                                    {
                                        d.description = jj;
                                    }
                                }
                                else
                                {
                                    d.description = description;
                                }
                            }
                            d.update();
                        }
                        dc = Document_Content.find(" did =" + d.Id).first();
                        if (dc != null)
                        {
                            dc.wapcontent = attrname;
                            dc.update();
                        }
                        else
                        {
                            dc = new Document_Content();
                            dc.did = d.Id;
                            dc.wapcontent = attrname;
                            dc.insert();
                        }
                        #endregion
                        break;

                    default:
                        switch (row.inputtype)
                        {
                            case "htmltext":
                                attrname = StringHelper.TextToHTML(attrname);
                                break;

                            case "img":
                                if (attrname.StartsWith("../"))
                                {
                                    attrname = Right(attrname, attrname.Length - 3);
                                }
                                break;

                            case "editor":
                                attrname = ctx.PostHtmlAll(row.attrname);
                                break;
                        }
                        var ism = Model_Att.find(" mid = 0 and  issys = 0 and attrname=:a").set("a", row.attrname).first();
                        if (ism != null)
                        {
                            dsql += "update ybb_document set " + row.attrname + " = '" + attrname + "' where Id =" + d.Id + ";";
                        }
                        else
                        {
                            var da = Document_Attr.find("  did =" + d.Id).first();
                            if (da != null)
                            {
                                if (!attrname.StrIsNullOrEmpty())
                                {
                                    dasql += row.attrname + " = '" + attrname + "',";
                                }
                            }
                            else
                            {
                                if (!attrname.StrIsNullOrEmpty())
                                {
                                    dasql1 += row.attrname + ",";
                                    dasql2 += "'" + attrname + "',";
                                }
                            }
                        }
                        break;
                }
            }
            //ctx.web.ResponseWrite(sql);
            //ctx.web.ResponseEnd();
            if (!dsql.StrIsNullOrEmpty())
            {
                db.RunSql<Document>(dsql);
            }
            if (!dasql.StrIsNullOrEmpty())
            {
                dsql = "update ybb_document_attr set " + dasql.TrimEnd(',') + " where did =" + d.Id + ";";
                db.RunSql<Document_Attr>(dsql);
            }
            else if (!dasql1.StrIsNullOrEmpty())
            {
                dsql = "insert into ybb_document_attr (did ," + dasql1.TrimEnd(',') + ") values (" + d.Id + "," + dasql2.TrimEnd(',') + ");";
                db.RunSql<Document_Attr>(dsql);
            }
            var albumlist = ctx.Post("albumlist");
            var albumliststr = albumlist.SplitString("|");
            var picname = ctx.Post("picname[]");
            var picnamestr = picname.SplitString();
            var filedes = ctx.Post("filedes[]");
            var filedesstr = filedes.SplitString();
            if (albumliststr.Length > 0)
            {
                Document_Album.deleteBatch(" did = " + d.Id);
                for (var i = 0; i < albumliststr.Length - 1; i++)
                {
                    var documentalbum = new Document_Album();
                    documentalbum.did = d.Id;
                    if (picnamestr.Length == 0)
                    {
                        documentalbum.picname = string.Empty;
                    }
                    else
                    {
                        documentalbum.picname = picnamestr[i];
                    }
                    if (filedesstr.Length == 0)
                    {
                        documentalbum.filedes = string.Empty;
                    }
                    else
                    {
                        documentalbum.filedes = filedesstr[i];
                    }
                    documentalbum.picfile = albumliststr[i];
                    documentalbum.addtime = DateTime.Now;
                    documentalbum.insert();
                }
            }
            else
            {
                Document_Album.deleteBatch(" did = " + d.Id);
            }
            if (ctx.HasErrors)
            {
                ctx.web.ResponseWrite(ctx.errors.ErrorsText);
            }
            else
            {
                ctx.web.ResponseWrite("true");
            }
            ctx.web.ResponseEnd();
        }

        [HttpPost]
        public virtual void ArticleDel()
        {
            string Ids = ctx.PostIdList("articleselectinfoid");
            string condition = string.Format("Id in ({0})", Ids);
            if (db.deleteBatch<Document>(condition) > 0)
            {
                logService.Add((User)ctx.viewer.obj, lang("article_del_log") + lang("log_extra_ok"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("article_del_log") + lang("log_extra_no"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

        [HttpPost]
        public virtual void ArticleSort()
        {
            var infoid = ctx.PostIdList("infoid");
            var pid = ctx.PostIdList("pid");
            var strArray = infoid.Split(new char[] { ',' });
            var strArray1 = pid.Split(new char[] { ',' });
            for (int i = 0; i < strArray.Length; i++)
            {
                string condition = string.Format("Id = {0}", strArray[i]);
                db.updateBatch<Document>("set pid=" + strArray1[i], condition);
            }
            logService.Add((User)ctx.viewer.obj, lang("article_sort_log") + lang("log_extra_ok"), "{Id:" + infoid + "'}", "", ctx.Ip);
            ctx.web.ResponseWrite("true");
            ctx.web.ResponseEnd();
        }

        [HttpGet, HttpPost]
        public virtual void ArticleSetting()
        {
            string Ids = ctx.PostIdList("articleselectinfoid");
            string condition = string.Format("Id in ({0})", Ids);
            var value = ctx.Post("value");
            var dbname = ctx.Post("dbname");
            db.updateBatch<Document>("set " + dbname + "=" + value, condition);
            if (!ctx.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("modelmanage_edit_log") + lang("log_extra_ok"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("modelmanage_edit_log") + lang("log_extra_no"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

        [HttpPost]
        public virtual void CreateHtml()
        {
            string Ids = ctx.PostIdList("articleselectinfoid");
            if (configsService.GetValue("is_html") == "1")
            {
                var list = Document.find(" id in (" + Ids + ")").list();
                foreach(var row in list)
                {
                    HtmlMaker.GetRead().Process(row, row.lng);
                }
                ctx.web.ResponseWrite("true");
            }
            else
            {
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void DoclabelList()
        {
            var mid = ctx.GetInt("mid");
            var builder = new StringBuilder();
            builder.Append("<input type=\"radio\" value=\"0\" checked=\"checked\" name=\"dlid\"/> 全部&nbsp;");
            var labellsit = new List<Document_Label>();
            if (mid > 0)
            {
                labellsit = Document_Label.find(" mid =:m and lng =:l").set("m", mid).set("l", DefaultLng).list();
            }
            else
            {
                labellsit = Document_Label.find(" lng =:l").set("l", DefaultLng).list();
            }
            var j = 0;
            foreach (var row in labellsit)
            {
                j++;
                builder.Append("								<input type=\"radio\" name=\"dlid\" value=\"" + row.Id + "\"/> " + row.labelname + "&nbsp;");
                if (j % 5 == 0) builder.Append("								<br />");
            }
            ctx.web.ResponseWrite(builder.ToString());
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void LinkList()
        {
            var didstr = ctx.Get("did");
            var list = Document.find(" Id in (" + didstr + ")").list();
            var builder = new StringBuilder();
            foreach (var row in list)
            {
                builder.AppendLine("<li id=\"didlinklist" + row.Id + "\">" + row.title + " <span class=\"del\" onclick=\"delinfolist('didlinklist" + row.Id + "','" + row.Id + "','linkdid')\">删除</span></li>");
            }
            ctx.web.ResponseWrite(builder.ToString());
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void ArticleBatchAdd()
        {
            SetPublic();
            setpublic();
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            set("refalse", "1");
            set("tab", "true");
            set("mid", ctx.Get("mid"));
            set("tid", ctx.Get("tid"));
            var upfile_pictype = String.Empty;
            var strArray = configsService.GetValue("upfile_pictype").SplitString("|");
            for (int i = 0; i < strArray.Length; i++)
            {
                upfile_pictype += ";*." + strArray[i];
            }
            var filetypes = configsService.GetValue("upfile_pictype").GetReplace("|", "、");
            set("filetypes", filetypes);
            set("MaxFile2", configsService.GetTextName("upfile_maxsize"));
        }

        [HttpGet]
        public virtual void BatchUpFile()
        {
            var upfile_pictype = String.Empty;
            var strArray = configsService.GetValue("upfile_pictype").SplitString("|");
            for (int i = 0; i < strArray.Length; i++)
            {
                upfile_pictype += ";*." + strArray[i];
            }
            set("upfile_pictype", upfile_pictype);
            set("MaxFile2", configsService.GetValue("upfile_maxsize").ToInt());
            var ybb_admininfo = (User)ctx.viewer.obj;
            set("UploadPage", to(new OtherController().FileUp) + "?ybb_admininfo=" + DES.Encrypt(ybb_admininfo.Name, "") + "&ybb_powerlist=" + DES.Encrypt(ybb_admininfo.GroupId.ToString(), "") + "&tid=" + ctx.GetInt("tid") + "&mid=" + ctx.GetInt("mid") + "&lng=" + DefaultLng);
            set("dir", sys.Path.Root);
        }

        [HttpGet, HttpPost]
        public virtual void MessageList()
        {
            SetPublic();
            setpublic();
            set("load", to(new AdminController().Load) + "?");
            set("view", to(new QycmsController().Admin_Tab_List));
            var condition = " lng='" + DefaultLng + "'";
            DataPage<Document_Message> list = null;
            Int32 maxperpage = ctx.PostInt("MaxPerPage");
            Int32 page_id = ctx.PostInt("page_id") + 1;
            String limitkey = ctx.Get("limitkey");
            String limitclass = ctx.Get("limitclass");
            var isclass = ctx.GetInt("isclass");
            switch (isclass)
            {
                case 1:
                    condition += " and isclass = 1 ";
                    break;

                case 2:
                    condition += " and isclass = 0 ";
                    break;
            }
            var isreply = ctx.GetInt("isreply");
            switch (isreply)
            {
                case 1:
                    condition += " and isreply = 1 ";
                    break;

                case 2:
                    condition += " and isreply = 0 ";
                    break;
            }
            if (strUtil.IsNullOrEmpty(limitkey)) limitkey = "id";
            if (strUtil.IsNullOrEmpty(limitclass)) limitclass = "desc";
            condition += " order by " + limitkey + " " + limitclass;
            CurrentRequest.setCurrentPage(page_id);
            list = Document_Message.findPage(condition, maxperpage);
            if (ctx.web.postValueAll().Count == 0)
            {
                ctx.web.ResponseWrite(list.RecordCount.ToString());
                ctx.web.ResponseEnd();
            }
            bind("list", list.Results);
        }

        [HttpGet]
        public virtual void MessageEdit(Int64 Id)
        {
            SetPublic();
            setpublic();
            target(MessageEditDo, Id);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            set("type", ctx.Get("type"));
            var lng = DefaultLng;
            set("lng", lng);
            var read = Document_Message.findById(Id);
            set("read", read);
            var articleread = Document.findById(read.did);
            set("articelread", articleread);
        }

        [HttpPost]
        public virtual void MessageEditDo(Int64 Id)
        {
            var recontent = ctx.Post("recontent");
            var dm = Document_Message.findById(Id);
            dm.recontent = recontent;
            dm.isreply = 1;
            dm.retime = DateTime.Now;
            Result result = dm.update();
            if (!ctx.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("acmessagelmain_edit_log") + lang("log_extra_ok"), "{Id:" + dm.Id + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("acmessagelmain_edit_log") + lang("log_extra_no"), "{Id:" + dm.Id + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

        [HttpPost]
        public virtual void MessageDel()
        {
            string Ids = ctx.PostIdList("selectinfoid");
            string condition = string.Format("Id in ({0})", Ids);
            if (db.deleteBatch<Document_Message>(condition) > 0)
            {
                logService.Add((User)ctx.viewer.obj, lang("acmessagelmain_del_log") + lang("log_extra_ok"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("acmessagelmain_del_log") + lang("log_extra_no"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

        [HttpPost]
        public virtual void MessageSetting()
        {
            string Ids = ctx.PostIdList("selectinfoid");
            string condition = string.Format("Id in ({0})", Ids);
            var value = ctx.Post("value");
            var dbname = ctx.Post("dbname");
            db.updateBatch<Document_Message>("set " + dbname + "=" + value, condition);
            if (!ctx.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("acmessagelmain_setting_log") + lang("log_extra_ok"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("acmessagelmain_setting_log") + lang("log_extra_no"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

        private bool a(string A_0)
        {
            string str = A_0.ToLower();
            if (str.StartsWith(configsService.GetValue("domain").ToLower()))
            {
                return true;
            }
            else if (str.StartsWith("http://"))
            {
                return false;
            }
            return true;
        }

        private string SiteUrl()
        {
            var siteurl = configsService.GetValue("domain");
            if (siteurl.StartsWith("http://")) siteurl = Right(siteurl, siteurl.Length - 7);
            if (siteurl.EndsWith("/")) siteurl = Left(siteurl, siteurl.Length - 1);
            if (siteurl.StartsWith("www.")) siteurl = Right(siteurl, siteurl.Length - 4);
            return siteurl;
        }

        private string SaveLocalImage(string imgPath)
        {
            var FilePath = configsService.GetValue("upfile_dir") + DateTime.Now.ToString("yyyy/MM/dd/", DateTimeFormatInfo.InvariantInfo);
            var FileName = (DateTime.Now.ToString("yyyyMMddHHmmss", CultureInfo.CurrentCulture) + "_" + Rand.MakeRandomString("0123456789", 3));
            var fileextname = System.IO.Path.GetExtension(imgPath).ToLower();
            if (!FileSystemObject.IsExist(PathHelper.Map(sys.Path.Root + FilePath), FsoMethod.Folder))
            {
                FileSystemObject.Create(PathHelper.Map(sys.Path.Root + FilePath), FsoMethod.Folder);
            }
            var OFilePath = sys.Path.Root + FilePath + FileName + fileextname;
            System.Net.WebClient client = new System.Net.WebClient();
            try
            {
                client.DownloadFile(imgPath, PathHelper.Map(OFilePath));
                return OFilePath;
            }
            catch
            {
                client.Dispose();
                return string.Empty;
            }
        }
    }
}
